package com.tbs.easyhomemoneyserver.auths

import com.tbs.easyhomemoneyserver.DO.ApiLimit
import com.tbs.easyhomemoneyserver.DO.UserRights
import com.tbs.easyhomemoneyserver.constants.BeanNameConstants.CONTAIN_RIGHTS_AUTH
import com.tbs.easyhomemoneyserver.constants.CommonConstants.ENABLE
import com.tbs.easyhomemoneyserver.interfaces.IRightAuthorization
import com.tbs.easyhomemoneyserver.model.rights.ApiRequest
import com.tbs.easyhomemoneyserver.model.rights.UserRightTable
import org.apache.dubbo.config.annotation.DubboService
import java.util.*
import java.util.function.Function
import java.util.stream.Collectors

/**
 * @author tongj
 */
@DubboService(group = CONTAIN_RIGHTS_AUTH)
open class SimpleContainsAuth : IRightAuthorization {
    override fun auth(limit: ApiLimit, apiRequest: ApiRequest): Boolean {
        if (ENABLE != limit.forceNeedFlag) {
            return true
        }
        val userRights = Optional.ofNullable<UserRightTable>(apiRequest.userOwnsRights)
            .map<Map<Long, UserRights?>> { `val`: UserRightTable ->
                `val`.indexRoleType(limit.roleType).indexRole(limit.role).select().stream().collect(
                    Collectors.toMap<UserRights, Long, UserRights?>(Function<UserRights, Long> {
                        return@Function it.rightsId
                    }, Function<UserRights, UserRights?> { r: UserRights? -> r })
                )
            }.orElse(HashMap<Long, UserRights?>())
        return userRights.containsKey(limit.id)
    }

    override fun unAuthedText(request: ApiRequest, noPassRights: ApiLimit): String {
        return String.format(
            "用户 %s 不存在权限:%s 权限备注:%s",
            if (request.userInfo == null) "未登录用户" else request.userInfo!!.name,
            noPassRights.role,
            noPassRights.comment
        )
    }
}
